package cuShapes;

import java.util.LinkedList;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import palette.CanvasManager;
import palette.CanvasWindow;
import xml.ConnectableAdapter;

@XmlTransient
public abstract class Connectable extends PQShape{

	/**
	 * 
	 */
	@XmlTransient
	private static final long serialVersionUID = -7715884783835885934L;
	/*
	 * Connections contains all connectable shapes
	 * whose arrows BEGIN at the current connectable
	 */
	@XmlJavaTypeAdapter(ConnectableAdapter.class)
	@XmlElementWrapper(name = "ConnectedTo")
	@XmlElement(name = "Connectable")
	protected LinkedList<Connectable> connections;
	
	protected Connectable(){
		super(((CanvasWindow) CanvasManager.getInst().getSelectedFrame()).getShapeId());
		((CanvasWindow) CanvasManager.getInst().getSelectedFrame()).incShapeId();
		//System.out.println("Connect con");
		connections = new LinkedList<Connectable>();
	}
	
	public void addConnection(Connectable c){
		connections.add(c);
	}
	
	public LinkedList<Connectable> getConnections() {
		return connections;
	}

	// Only for use with XmlReader and reopening files. The method just gets the shapeId of 
	// each shape inside connections and searches for that id inside of the currWin's shapeList.
	// When it finds that shape it adds a new connection to a new connections LinkedList called tempC.
	// When the original connections has been iterated the new connections list, tempC is assigned 
	// to connections.
	public void reAddConnections() {
		int tempId;
		LinkedList<Connectable> tempC = new LinkedList<Connectable>();
		CanvasWindow currWin = (CanvasWindow) CanvasManager.getInst().getSelectedFrame();
		
		for(Connectable x : connections) {
			tempId = x.getShapeId();
			tempC.add(currWin.getShapeList().getShape(tempId));
		}
		
		// might need to do garbage collection on old connections that just got replaced with tempC
		connections = tempC;
	}
}
